<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Models\Auth;
use Illuminate\Support\Facades\Cache;
class AuthController extends BaseController
{
    //权限类表
    public function index(Request $request){
        return view('admin.auth.index');
    }
    //权限列表信息
    public function info(){
        $data = Auth::setTableTree();
        return $this->showList($data,count($data));
    }
    //添加权限
    public function add(Request $request){
        if($request->isMethod('post')){
            $arr = $request->except('_token');
            if($request->boolean('is_show')){
                $arr['is_show'] = '1';
            }else{
                $arr['is_show'] = '0';
            }
            $arr['create_id'] = $arr['last_update_id'] = session('user.id');
            $arr['create_time'] = $arr['update_time'] = date('Y-m-d H:i:s',time());
            if(Auth::insert($arr)){
                //清楚缓存
                Cache::flush();
                return $this->success('添加成功',asset('/auth/index'));
            }else{
                return $this->error('添加失败');
            }

        }
        //权限上级分类id
        $id = $request->get('id',0);
        //权限列表 select使用
        $authList = Auth::setAuthList();
        return view('admin.auth.add',['authList'=>$authList,'id'=>$id]);
    }

    //编辑权限
    public function edit(Request $request){
        if($request->isMethod('post')){
            $arr = $request->except(['_token','id']);
            $id = $request->input('id');
            if((int)$id <= 0 ){
                return $this->error('数据丢失');
            }
            if($request->boolean('is_show')){
                $arr['is_show'] = '1';
            }else{
                $arr['is_show'] = '0';
            }
            $arr['last_update_id'] = session('user.id');
            $arr['update_time'] = date('Y-m-d H:i:s',time());
            if(Auth::where('id','=',$id)->update($arr)){
                Cache::flush();
                return $this->success('编辑成功',asset('/auth/index'));
            }else{
                return $this->error('编辑失败');
            }

        }
        //权限上级分类id
        $id = $request->get('id',0);
        //获取编辑权限详细信息
        $authinfo = Auth::find($id);
        //权限列表 select使用
        $authList = Auth::setAuthList();
        return view('admin.auth.edit',['authList'=>$authList,'authinfo'=>$authinfo]);
    }
    //删除权限
    public function del(Request $request){
        if($request->has('id') && (int)$request->input('id') > 0){
           $id = $request->input('id');
           //数据库只更改了顶级状态
            if(Auth::where('id','=',$id)->update(['status'=>'0'])){
                Cache::flush();
                return $this->success('删除成功',asset('/auth/index'));
            }
            return $this->error('删除失败');
        }
        return $this->error('参数无效');
    }
    //获取id
}
